﻿using MediatR;
using MES.Bom.API.Application.Command.物料命令;
using MES.Bom.Domain;
using MES.Bom.ErrorCode;
using MES.Bom.Infrastructure;
using Microsoft.EntityFrameworkCore;

namespace MES.Bom.API.Application.CommandHandler.物料命令处理
{
    /// <summary>
    /// 物料选择列表命令处理器
    /// </summary>
    public class MaterailQueryCommandHandler : IRequestHandler<MaterailQueryCommand, APIResult<APIPaging<Material>>>
    {
        private readonly IBaseRepository<Material> materailRepository;
        private readonly ILogger<MaterailQueryCommandHandler> logger;
        public MaterailQueryCommandHandler(IBaseRepository<Material> materailRepository, ILogger<MaterailQueryCommandHandler> logger = null)
        {
            this.materailRepository = materailRepository;
            this.logger = logger;
        }

        public Task<APIResult<APIPaging<Material>>> Handle(MaterailQueryCommand request, CancellationToken cancellationToken)
        {
            try
            {
                APIResult<APIPaging<Material>> result = new APIResult<APIPaging<Material>>();
                APIPaging<Material> paging=new APIPaging<Material>();
                var list = materailRepository.GetValues().AsNoTracking();
                if (!string.IsNullOrEmpty(request.MaterialCode)) 
                {
                    list = list.Where(x => x.MaterialCode == request.MaterialCode);
                }
                if (!string.IsNullOrEmpty(request.MaterialName))
                {
                    list = list.Where(x => x.MaterialName.Contains(request.MaterialName));
                }

                paging.TotalCount = list.Count();
                paging.TotalPages = (int)Math.Ceiling(paging.TotalCount * 1.0 / request.PageSize);
                paging.List=list.OrderByDescending(x=>x.CreateTime).Skip((request.PageIndex-1)*request.PageSize).Take(request.PageSize).ToList();
                result.Code = APIEnums.Success;
                result.Message = "获取成功";
                result.Data = paging;
                return Task.FromResult(result);

            }
            catch (Exception ex)
            {

                throw;
            }
        }
    }
}
